package com.ruoyi.system.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * @author zhubayi
 * 七牛云工具类
 */
@Slf4j
public class AliUtils {
//    static String endpoint = "oss-cn-hangzhou.aliyuncs.com";
//    static String accessKeyId = "STS.NUdC6Xn858tKbagxcgFspzR6g";
//    static String accessKeySecret = "BFWmWdK1vhn65dHqTR7y6eZPksJpbJyuBLRY4E9hBF7p";
//    static String bucketName = "pxb7-img-0";
//    static String securityToken = "pxb7-img-0";

    public static byte[] downloadPicture(String url) {
        URL urlConnection = null;
        HttpURLConnection httpURLConnection = null;
        try {
            urlConnection = new URL(url);
            httpURLConnection = (HttpURLConnection) urlConnection.openConnection();
            InputStream in = httpURLConnection.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            in.close();
            out.close();
            return out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpURLConnection.disconnect();
        }
        return null;
    }
    //二进制文件转换MultipartFile
    public static MultipartFile getMultipartFile(String name, byte[] bytes) {
        MultipartFile mfile = null;
        ByteArrayInputStream in = null;
        try {
            in = new ByteArrayInputStream(bytes);
            FileItemFactory factory = new DiskFileItemFactory(16, null);
            FileItem fileItem = factory.createItem("mainFile", "text/plain", false, name);
            IOUtils.copy(new ByteArrayInputStream(bytes), fileItem.getOutputStream());
            mfile = new CommonsMultipartFile(fileItem);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mfile;
    }
    public static String uploadFile(MultipartFile file,String endpoint,String accessKeyId,
                                    String accessKeySecret,String bucketName,String securityToken,
                                    String viewDomain
                                        ) throws Exception {
        try {
            // 创建OSS实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret,securityToken);

            // 获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            // 获取文件名称
            String fileName = file.getOriginalFilename();

            // 以下操作主要是把上传的文件分类放到oss存储，这样防止上传相同的文件名，会把前一个文件覆盖掉。 start
            // 在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // yuy76t5rew01.jpg
            fileName = uuid + fileName;
            // 2 把文件按照日期进行分类
            // 获取当前日期,格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String datePath = sdf.format(new Date());
            SimpleDateFormat sdfs = new SimpleDateFormat("yyyyMMddHHmmss");
            String datePaths = sdfs.format(new Date());
            datePath = datePath+"/"+datePaths;
            Random random = new Random();
            // 生成四位随机数
            int randomNum = random.nextInt(9000) + 1000;;
            // 拼接
            datePath = datePath+"_"+randomNum;
            fileName = "images/merchantProduct/"+datePath+ ".tencent";
//            https://images.pxb7.com/images/merchantProduct/20240305/20240305013549_8316.jpg
            // end
            // 调用oss方法实现上传
            // 第一个参数 Bucket名称
            // 第二个参数 上传到oss文件路径和文件名称
            // 第三个参数 上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();

            // 把上传之后文件路径返回，需要把上传到阿里云oss路径手动拼接出来
//            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            String url = viewDomain + "/" + fileName;
            return url;
        } catch (Exception e) {
            return "";
        }
    }


    public static String uploadFile(MultipartFile file, String endpoint, String accessKeyId,
                                    String accessKeySecret, String bucketName, String securityToken
    ) throws Exception {
        try {
            // 创建OSS实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);

            // 获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            // 获取文件名称
            String fileName = file.getOriginalFilename();

            // 以下操作主要是把上传的文件分类放到oss存储，这样防止上传相同的文件名，会把前一个文件覆盖掉。 start
            // 在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // yuy76t5rew01.jpg
            fileName = "goodsPublish/" + uuid + fileName;

//            fileName = DigestUtils.md5Hex(fileName);
//            https://images.pxb7.com/images/merchantProduct/20240305/20240305013549_8316.jpg
            // end
            // 调用oss方法实现上传
            // 第一个参数 Bucket名称
            // 第二个参数 上传到oss文件路径和文件名称
            // 第三个参数 上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();

            // 把上传之后文件路径返回，需要把上传到阿里云oss路径手动拼接出来
            String uploadUrl = fileName;
            return uploadUrl;
        } catch (Exception e) {
            System.out.println(e);
            return "";
        }
    }
}

